package models

import (
	"errors"
	"gitee.com/kudingc/role_proxy/common"
)

type LoginReq struct {
	UserName     string `json:"user_name"`
	Passwd       string `json:"passwd"`
	CaptchaId    string `json:"captcha_id"`
	CaptchaValue string `json:"captcha_value"`
}

type LoginRes struct {
	Authorization string      `json:"Authorization"`
	UserId        int         `json:"user_id"`
	UserCode      string      `json:"user_code"`
	UserName      string      `json:"user_name"`
	MenuList      interface{} `json:"menu_list"`
}

func (u *LoginReq) CheckUser() (user SysUser, menuList []*SysMenuTree, err error) {
	var sysRoleMenu SysRoleMenu
	var roleIds string

	err = common.Db.QueryTable("sys_user").Filter("user_name__exact", u.UserName).Filter("passwd__exact", u.Passwd).Filter("state__exact", 1).One(&user)
	if user.Id == 0 || err != nil {
		return user, nil, errors.New("用户名或密码错误")
	}
	// 获取用户所拥有的menu列表
	sql := "select group_concat(role_id) roleIds from sys_user su LEFT JOIN sys_user_role sur ON su.id = sur.user_id WHERE su.id = ? group by su.id;"
	err = common.Db.Raw(sql, user.Id).QueryRow(&roleIds)
	if err != nil {
		return user, nil, err
	}
	menuList, err = sysRoleMenu.GetMenuTree(roleIds)
	return
}
